<template>
  <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-row>
          <el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
              <el-form-item label="所属党组织" prop="deptId" style="width: 100%;">
                <el-tree-select
                  v-model="queryParams.deptId"
                  :data="deptOptions"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  value-key="deptId"
                  placeholder="请选择所属党组织"
                  check-strictly
                />
              </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
              <el-form-item label="奖惩类别" prop="reward" style="width: 100%;">
                <el-select v-model="queryParams.reward" placeholder="请选择奖惩类别" clearable @change="changeSelectReward">
                  <el-option
                  v-for="dict in rewardOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 12px;">
              <el-form-item label="奖惩类型" prop="typeOrg" style="width: 100%;" v-if="isOrgRewardsBool">
                <el-select v-model="queryParams.typeOrg" placeholder="请选择奖惩类型" clearable>
                  <el-option
                  v-for="dict in typeOrgOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="奖惩类型" prop="typePerson" style="width: 100%;" v-else>
                <el-select v-model="queryParams.typePerson" placeholder="请选择奖惩类型" clearable>
                  <el-option
                  v-for="dict in typePersonOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
                </el-select>
              </el-form-item>
          </el-col>
      </el-row>
      <el-row>
          <el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
              <el-form-item label="年份" prop="year" style="width: 100%;">
                  <el-date-picker clearable
                      v-model="queryParams.year"
                      type="year"
                      value-format="YYYY"
                      placeholder="请选择年份"
                      style="width: 100%;">
                  </el-date-picker>
              </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 12px; padding-right: 12px;" v-if="!isOrgRewardsBool">
              <el-form-item label="党员姓名" prop="userName" style="width: 100%;">
                  <el-input
                  v-model="queryParams.userName"
                  placeholder="请输入党员姓名"
                  clearable
                  @keyup.enter="handleQuery"
                  />
              </el-form-item>
          </el-col>
      </el-row>
  </el-form>
  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button
        type="danger"
        icon="Plus"
        @click="handleAdd"
        v-hasPermi="['partybuilding:Honor:add']"
      >新增</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button
        icon="Download"
        @click="handleExport"
        v-hasPermi="['partybuilding:Honor:export']"
      >导出</el-button>
    </el-col>
    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
  </el-row>

  <el-table v-loading="loading" :data="HonorList" @selection-change="handleSelectionChange">
    <el-table-column label="所属组织" align="center" prop="deptName" />
    <el-table-column label="姓名" align="center" prop="userName" v-if="!isOrgRewardsBool"/>
    <el-table-column label="奖惩类别" align="center" prop="reward" >
      <template #default="scope">
          <el-tag type="success" v-if="scope.row.reward==1">{{ isOrgRewardsBool?'组织荣誉':'个人荣誉' }}</el-tag>
          <el-tag type="danger" v-else>{{ isOrgRewardsBool?'组织惩罚':'个人惩罚' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="奖惩类型" align="center" prop="typeOrg" >
      <template #default="scope">
          {{ isOrgRewardsBool? selectDictLabel(pb_org_reward, scope.row.typeOrg) : selectDictLabel(pb_member_reward, scope.row.typePerson) }}
      </template>
    </el-table-column>
    <el-table-column label="奖惩名称" align="center" prop="honor" />
    <el-table-column label="获得时间" align="center" prop="grantTime" />
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template #default="scope">
        <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['partybuilding:Honor:edit']">修改</el-button>
        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['partybuilding:Honor:remove']">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <pagination
    v-show="total>0"
    :total="total"
    v-model:page="queryParams.pageNum"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />


  <!-- 选择人员对话框 -->
  <select-people ref="userPeopleRef" :parentMethod="userPeopleMethod"></select-people>
  
  <!-- 添加或修改荣誉管理对话框 -->
  <el-dialog :title="title" v-model="open" width="50%" height="39%" append-to-body style="margin-top: 9px!important;">
    <el-form ref="HonorRef" :model="form" :rules="rules" label-width="80px" style="padding: 9px;">
      <el-row>
          <el-col :span="24" v-if="isOrgRewardsBool">
              <el-form-item label="所属组织" prop="deptId">
                  <el-tree-select
                      v-model="form.deptId"
                      :data="deptOptions"
                      :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                      value-key="deptId"
                      placeholder="请选择所属组织"
                      check-strictly
                      @node-click="handleClickOrginize"
                      :disabled="isDiabled"
                  />
              </el-form-item>
          </el-col>
          <el-col :span="24" v-else>
              <el-form-item label="奖惩人员" prop="userId">
                <el-input v-model="userNameList" @click="handleClickPeople" :disabled="userDisabled"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-radio-group v-model="form.reward" style="margin-left: 9%;margin-bottom: 13px" @change="changeRewardRadio" :disabled="isDiabled">
                <el-radio value="1" v-if="isOrgRewardsBool">组织荣誉</el-radio>
                <el-radio value="1" v-else>个人荣誉</el-radio>
                <el-radio value="0" v-if="isOrgRewardsBool">组织惩处</el-radio>
                <el-radio value="0" v-else>个人惩处</el-radio>
              </el-radio-group>
          </el-col>
          <el-col :span="12" v-if="isOrgRewardsBool">
              <el-form-item label="奖惩类型" prop="typeOrg" class="rewardTypeStyle">
                  <el-select v-model="form.typeOrg" placeholder="请选择奖惩类型" clearable style="width: 100%" @change="changeRewardType" :disabled="isDiabled">
                      <el-option
                      v-for="dict in typeOrgEditOptions"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"/>
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
              <el-form-item label="奖惩类型" prop="typePerson" class="rewardTypeStyle">
                  <el-select v-model="form.typePerson" placeholder="请选择奖惩类型" clearable style="width: 100%" @change="changeRewardType" :disabled="isDiabled">
                      <el-option
                      v-for="dict in typePersonEditOptions"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"/>
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="日期" prop="grantTime">
                  <el-date-picker clearable
                      v-model="form.grantTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择日期"
                      style="width: 100%"
                      @change="changeGrantTime"
                      :disabled="isDiabled">
                  </el-date-picker>
              </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="奖惩名称" prop="honor">
                  <el-input v-model="form.honor" placeholder="请输入奖惩名称" @blur="blurHonor" :disabled="isDiabled"/>
              </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="荣誉说明">
                  <el-input
                      v-model="form.content"
                      type="textarea"
                      :rows="4"
                      :disabled="isDiabled"
                  />
              </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="照片" prop="pictureUrl">
                <div v-if="isDiabled">
                  <el-image :src="baseUrl+form.pictureUrl" style="width: 100%;height: 250px;"></el-image>
                </div>
                <div v-else>
                  <image-upload
                      v-model="form.pictureUrl"
                      :multiple="true"
                      :limit="1"
                      :file-type="['jpg', 'png', 'jpeg']"
                      :file-size="200">
                  </image-upload>
                </div>
              </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="附件" prop="fileUrl">
                  <file-upload
                    v-model="form.fileUrl"
                    :multiple="true"
                    :limit="10"
                    :file-type="['doc', 'docx', 'pdf']"
                    :file-size="200"
                    :isDisabled="isDiabled">
                  </file-upload>
              </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <el-divider  style="margin: 0; border-top : 1px solid #e8e8e8;"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!isDiabled">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { listHonor, getHonor, delHonor, addHonor, updateHonor } from "@/api/partybuilding/Honor";
import { listOrg } from "@/api/partybuilding/Org";
import SelectPeople from '../../MeetingInfo/component/SelectPeople.vue'
const props = defineProps({
  isOrgRewards: {
      type: Boolean,
      default: true
  }
})
const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const HonorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const isOrgRewardsBool = ref(false);
const rewardOptions = ref([]);
const typeOrgOptions = ref([]);
const typePersonOptions = ref([]);
const typeOrgEditOptions = ref([]);
const typePersonEditOptions = ref([]);
const isEditHonor = ref(false);
const oldHonor = ref("");
const userIdList = ref([]);
const userNameList = ref([])
const deptName = ref("");
const userDisabled = ref(false);
const userPeopleRef = ref(null);
const isDiabled = ref(false);

const { pb_org_reward } = proxy.useDict("pb_org_reward");
const { pb_member_reward } = proxy.useDict("pb_member_reward");

// 获取奖惩类型选项
function getRewardTypeOptions(val) {
  if (isOrgRewardsBool.value) {
      let tmpArray = [{value: null, label: '全部'}];
      //组织奖惩
      if (val == '1'){
        //0惩处，1奖励
        pb_org_reward.value.forEach(item => {
          if (item.value > 0){
            tmpArray.push(item);
          }
        });
      }else{
        pb_org_reward.value.forEach(item => {
          if (item.value < 0){
            tmpArray.push(item);
          }
        });
      }
      typeOrgEditOptions.value = tmpArray;
  } else {
      let tmpArray = [{value: null, label: '全部'}];
      //个人奖惩
      if (val == '1'){
        //0惩处，1奖励
        pb_member_reward.value.forEach(item => {
          if (item.value > 0){
            tmpArray.push(item);
          }
        });
      }else{
        pb_member_reward.value.forEach(item => {
          if (item.value < 0){
            tmpArray.push(item);
          }
        });
      }
      typePersonEditOptions.value = tmpArray;
  }
}

// 切换奖惩类型
function changeRewardRadio(val) {
  form.value.typePerson = null;
  form.value.typeOrg = null;
  getRewardTypeOptions(val);
}

//奖罚类型切换
function changeRewardType(val) {
  if (!isEditHonor.value) {
    let curTime = new Date();
    let year = curTime.getFullYear();
    if (form.value.grantTime!=null){
      year = form.value.grantTime.split("-")[0];
    }
    let honorTypeName = "";
    if (isOrgRewardsBool.value) {
      honorTypeName = typeOrgEditOptions.value.find(item => item.value == val).label;
    } else {
      honorTypeName = typePersonEditOptions.value.find(item => item.value == val).label;
    }
    form.value.honor = year+honorTypeName;
    oldHonor.value = form.value.honor;
  }
}

function changeGrantTime(val) {
  if (!isEditHonor.value) {
    if (val!=null){
      let year = val.split("-")[0];
      let honorTypeName = "";
      if (isOrgRewardsBool.value) {
        honorTypeName = typeOrgEditOptions.value.find(item => item.value == form.value.typeOrg).label;
      } else {
        honorTypeName = typePersonEditOptions.value.find(item => item.value == form.value.typePerson).label;
      }
      form.value.honor = year+honorTypeName;
      oldHonor.value = form.value.honor;
    }
  }
}

function blurHonor() {
  if (oldHonor.value!=null && oldHonor.value.length > 0 && oldHonor.value!= form.value.honor) {
    isEditHonor.value = true;
  }
}

//获取编辑页面奖惩类型
function getEditTypeOptions() {
  if (isOrgRewardsBool.value) {
    typeOrgEditOptions.value = pb_org_reward.value;
  } else {
    typePersonEditOptions.value = pb_member_reward.value;
  }
}

//查询条件-奖惩类别
function changeSelectReward(val) {
  if (isOrgRewardsBool.value) {
      let tmpArray = [{value: null, label: '全部'}];
      //组织奖惩
      if (val == '1'){
        //0惩处，1奖励
        pb_org_reward.value.forEach(item => {
          if (item.value > 0){
            tmpArray.push(item);
          }
        });
      }else{
        pb_org_reward.value.forEach(item => {
          if (item.value < 0){
            tmpArray.push(item);
          }
        });
      }
      typeOrgOptions.value = tmpArray;
  } else {
      let tmpArray = [{value: null, label: '全部'}];
      //个人奖惩
      if (val == '1'){
        //0惩处，1奖励
        pb_member_reward.value.forEach(item => {
          if (item.value > 0){
            tmpArray.push(item);
          }
        });
      }else{
        pb_member_reward.value.forEach(item => {
          if (item.value < 0){
            tmpArray.push(item);
          }
        });
      }
      typePersonOptions.value = tmpArray;
  }
}

onMounted(() => {
  isOrgRewardsBool.value = props.isOrgRewards;
  if (isOrgRewardsBool.value) {
      title.value = "组织奖惩";
      rewardOptions.value = [{value: null, label: '全部'},{value: 1, label: '组织荣誉'},{value: 0, label: '组织惩处'}];
  } else {
      title.value = "个人奖惩";
      rewardOptions.value = [{value: null, label: '全部'},{value: 1, label: '个人荣誉'},{value: 0, label: '个人惩处'}];
  }
  getList();
})

const data = reactive({
form: {},
queryParams: {
  pageNum: 1,
  pageSize: 10,
  deptName: null,
  deptId: null,
  honor: null,
  reward: null,
  teamHonor: null,
  typeOrg: null,
  grantTime: null,
  content: null,
  pictureUrl: null,
  fileUrl: null,
  typePerson: null,
  userId: null,
  userName: null,
  status: null,
  year: null
},
queryPeopleParams: {
  pageNum: 1,
  pageSize: 900,
  deptId: null,
},
rules: {
  deptId: [
    { required: true, message: "所属组织不能为空", trigger: ["blur", "change"] }
  ],
  typeOrg: [
    { validator: checkTypeOrg, trigger: ["blur", "change"] }
  ],
  typePerson: [
    { validator: checkTypePerson, trigger: ["blur", "change"] }
  ],
  grantTime: [
    { required: true, message: "日期不能为空", trigger: ["blur", "change"] }
  ],
  honor: [
    { required: true, message: "荣誉名称不能为空", trigger: ["blur", "change"] }
  ],
  pictureUrl1: [
    { required: true, message: "照片不能为空", trigger: ["blur", "change"] }
  ],
}
});

const { queryParams, queryPeopleParams, form, rules } = toRefs(data);

// 验证组织奖惩类型
function checkTypeOrg(rule, value, callback) {
  if (isOrgRewardsBool.value) {
      if (value == null) {
          callback(new Error("请选择奖惩类型"));
      } else {
          callback();
      }
  } else {
    callback();
  }
}

// 验证个人奖惩类型
function checkTypePerson(rule, value, callback) {
  if (isOrgRewardsBool.value) {
    callback();
  } else {
    if (value == null) {
        callback(new Error("请选择奖惩类型"));
    } else {
        callback();
    }
  }
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询部门下拉树结构 */
function getDeptTree() {
  listOrg().then(response => {
    deptOptions.value = proxy.handleTree(response.rows, "deptId");
  });
};

const refresh = () => {
    getList();
};

defineExpose({
    refresh
});

/** 查询荣誉管理列表 */
function getList() {
  loading.value = true;
  if (isOrgRewardsBool.value) {
    queryParams.value.teamHonor = 1;
  } else {
    queryParams.value.teamHonor = 0;
  }
  listHonor(queryParams.value).then(response => {
    HonorList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 获取组织名称
function handleClickOrginize(data) {
  form.value.deptName = data.label;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptName: null,
    deptId: null,
    honor: null,
    reward: null,
    teamHonor: null,
    typeOrg: null,
    grantTime: null,
    content: null,
    pictureUrl: null,
    fileUrl: null,
    typePerson: null,
    userId: null,
    userName: null,
    status: null
  };
  userNameList.value = [];
  userIdList.value = [];
  proxy.resetForm("HonorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


//单击人员
function handleClickPeople() {
  userPeopleRef.value.show();
}

//人员回调函数
function userPeopleMethod(uIdList, uNameList) {
  userIdList.value = uIdList;
  userNameList.value = uNameList;
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  //teamHonor : 0个人，1团队
  if (isOrgRewardsBool.value) {
    form.value.teamHonor = 1;
  } else {
    form.value.teamHonor = 0;
  }
  form.value.reward = '1';
  getRewardTypeOptions(form.value.reward);
  open.value = true;
  userDisabled.value = false;
  title.value = "添加荣誉管理";
}


/** 查看按钮操作 */
function handleView(row) {
  reset();
  getHonor(row.id).then(response => {
    form.value = response.data;
    form.value.reward = form.value.reward+'';
    getRewardTypeOptions(form.value.reward);
    form.value.typeOrg = form.value.typeOrg+'';
    form.value.typePerson = form.value.typePerson+'';
    userNameList.value = [form.value.userName];
    if (form.value.fileUrl!=null && form.value.fileUrl.length > 0){
      let arr = [];
      JSON.parse(form.value.fileUrl).forEach(item => {
        arr.push(item);
      });
      form.value.fileUrl = arr.join(",");
    }
    open.value = true;
    userDisabled.value = true;
    isDiabled.value = true;
    title.value = "查看荣誉管理";
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getHonor(row.id).then(response => {
    form.value = response.data;
    form.value.reward = form.value.reward+'';
    getRewardTypeOptions(form.value.reward);
    form.value.typeOrg = form.value.typeOrg+'';
    form.value.typePerson = form.value.typePerson+'';
    userNameList.value = [form.value.userName];
    if (form.value.fileUrl!=null && form.value.fileUrl.length > 0){
      let arr = [];
      JSON.parse(form.value.fileUrl).forEach(item => {
        arr.push(item);
      });
      form.value.fileUrl = arr.join(",");
    }
    open.value = true;
    userDisabled.value = true;
    isDiabled.value = false;
    title.value = "修改荣誉管理";
  });
}

function getJsonArrString(fileUrl){
  let arr = [];
  fileUrl.split(",").forEach(item => {
    arr.push(item);
  });
  return JSON.stringify(arr);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["HonorRef"].validate(valid => {
    if (valid) {
      //附件
      if (form.value.fileUrl!=null && form.value.fileUrl.length > 0){
        form.value.fileUrl = getJsonArrString(form.value.fileUrl);
      }
      if (form.value.id != null) {
        updateHonor(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        if (isOrgRewardsBool.value) {
          addHonor(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        } else {
            //人员转为JSON数组格式
            form.value.userIds = userIdList.value; // 奖惩人员ID
            addHonor(form.value).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
        }
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  let title = "";
  if (row.typePerson!=null) {
    title = "个人奖惩姓名为"+ row.userName;
  }else{
    title = "组织奖惩姓名为"+ row.deptName;
  }
  proxy.$modal.confirm('是否确认删除"' + title + '"的数据项？').then(function() {
    return delHonor(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('partybuilding/Honor/export', {
    ...queryParams.value
  }, `Honor_${new Date().getTime()}.xlsx`)
}

getDeptTree();
getList();
</script>

<style lang="scss" scoped>
.ant-form-extra {
  min-height: 22px;
  margin-top: 4px;
  color: rgba(0, 0, 0, .45);
  font-size: 14px;
  line-height: 1.5;
  transition: color .3s cubic-bezier(.215,.61,.355,1);
}
.rewardTypeStyle:before {
  color: var(--el-color-danger);
  content: "*";
  line-height: 32px;
  position: absolute;
  left: 3px;
}
.pagination-container {
  padding: 22px 20px !important;
}
</style>
